<template>
  <el-select
    v-model="organizationId"
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="true"
    :filterable="filterable"
    :remote="true"
    :remote-method="remoteMethod"
    :loading="loading"
    default-first-option
    v-selectScroll="handleScroll"
    @change="handleChange"
  >
    <el-option
      v-for="(item, index) in organizationList"
      :key="index"
      :label="item.organizationName"
      :value="item.entrustOrganizationId"
    ></el-option>
  </el-select>
</template>

<script>
import { entrustOrganizationListing2 } from '@/api/person/entrustOrganization'

export default {
  name: 'OrganizationSelect',
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    filterable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        organizationName: '',
      },
      organizationList: [],
      total: 0,
      hasMore: true,
    }
  },
  computed: {
    organizationId: {
      get() {
        return this.value
      },
      set(value) {
        this.$emit('input', value || '')
      }
    }
  },
  created() {
    this.getEntrustOrganizationList()
  },
  methods: {
    init() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.queryParams.organizationName = ''
      this.organizationId = ''
      this.organizationList = []
      this.total = 0
      this.hasMore = true
      this.getEntrustOrganizationList()
    },
    // 获取委托单位列表
    getEntrustOrganizationList() {
      entrustOrganizationListing2(this.queryParams).then(res => {
        this.loading = false
        this.organizationList.push(...(res.rows || []))
        this.total = res.total || 0
        this.hasMore = this.organizationList.length < this.total
      }).catch(err => {
        this.loading = false
      })
    },
    // 下拉框无限滚动
    handleScroll(isBottom) {
      if (isBottom && !this.loading && this.hasMore) {
        this.queryParams.pageNum += 1
        this.getEntrustOrganizationList()
      }
    },
    // 远程搜索
    remoteMethod(query) {
      this.organizationList = []
      this.queryParams.pageNum = 1
      this.queryParams.organizationName = query
      this.loading = true
      this.getEntrustOrganizationList()
    },
    // 设置默认项
    setDefaultOption(defaultOption) {
      const findRes = this.organizationList.find(item => item.entrustOrganizationId == defaultOption.entrustOrganizationId)
      if (!findRes) this.organizationList.unshift(defaultOption)
    },
    handleChange(value) {
      const findRes = this.organizationList.find(item => item.entrustOrganizationId == value)
      this.$emit('change', value, findRes)
    }
  }
}
</script>

<style scoped lang="scss">

</style>
